package network;
import java.io.*;
import java.net.*;

import protocol.Reply;
import protocol.Request;
import protocol.Request.commands;


public class NetworkManager {
	
	private Socket socket;
	private ObjectInputStream readStream;
	private ObjectOutputStream writeStream;
	
	
	
	public NetworkManager(String IPAddr, int port){
		try{
			socket = new Socket(IPAddr,port);
			writeStream = new ObjectOutputStream(socket.getOutputStream());
			readStream = new ObjectInputStream(socket.getInputStream());
			//readStream.;
			
			System.out.println(IPAddr+ " is Connected ");
			
		}catch(IOException e){
			e.printStackTrace();
			System.err.println("Server : "+IPAddr+" is not Connected ");
			System.err.println("Exit ......... ");
			//System.exit(0);
		}
		
	}
	public void close()
	{
		try{
			socket.close();
			System.out.println("disconnection succees"); 
		}catch(Exception e){
			System.err.println(e);
		}
	}
	public void SendRequest(commands com, String[] arg)
	{
		Request re = null;
		if(arg==null)
			re = new Request(com);
		else
			re = new Request(com , arg);
		try{			
			writeStream.flush();
		}catch(Exception e){
			System.err.println(e);
		}
		try{			
			writeStream.writeObject(re);
			writeStream.flush();
		}catch(Exception e){
			System.err.println(e);
		}
	}
	public Reply GetReply()
	{
		Reply tmp = null;
		try{
			tmp = (Reply)readStream.readObject();			
		}catch(Exception e){
			System.err.println(e);
		}
		try{
			readStream.reset();		
		}catch(Exception e){
			System.err.println(e);
		}
		
		return tmp;
	}
	
}
